package org.openrbac.rbac.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import org.openrbac.rbac.constant.CommonConstant;
import org.openrbac.rbac.utils.JwtUtil;
import org.openrbac.rbac.vo.R;
import org.openrbac.rbac.utils.RedisUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author bapie
 */
@Component
@AllArgsConstructor
public class SecurityAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    private ObjectMapper objectMapper;
    private JwtUtil jwtUtil;
    private RedisUtil redisUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        redisUtil.hashSet(CommonConstant.TOKEN_KEY, authentication.getName(), authentication, 24*60*60L);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(R.ok("登陆成功", jwtUtil.createJwt(authentication.getName()))));
    }
}
